package com.cst.intercepterdemo.chain.builder;

import com.cst.intercepterdemo.exceptions.IntercepterFetchException;
import com.cst.intercepterdemo.intercepter.IRequestIntercepter;
import com.cst.intercepterdemo.mapper.ValidatorMapper;
import com.cst.intercepterdemo.model.Validator;
import com.cst.intercepterdemo.model.ValidatorExample;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.util.List;

/**
 * <ul>
 * <li>文件名称 : com.cst.intercepterdemo.chain.builder.AbstractChainBuilder
 * </li>
 * <li>版权所有 : 版权所有(C)2016-2020</li>
 * <li>公 司 : CST</li>
 * <li>创建时间 : 2016/12/8</li>
 * <li>修改记录 : </li>
 * </ul>
 * 类说明：
 *
 * @author Allen
 * @version 1.0
 */
public abstract class AbstractBeanChainBuilder implements IChainBuilder{

    @Autowired
    private ApplicationContext context;

    @Autowired
    private ValidatorMapper validatorDao;

    /**
     * 获取指定名称的拦截器
     * @param name intercepter名称
     * @return 拦截器bean
     */
    protected IRequestIntercepter getIntercepterByName(String name){

        /**
         * 先通过nickname找，如果找不到则获得Validator的ClassName查找
         */
        Object bean = null;
        try {
            bean = context.getBean(name);
        } catch (BeansException e) {
        }

        if(bean==null){
            ValidatorExample example = new ValidatorExample();
            example.createCriteria().andNicknameEqualTo(name);
            List<Validator> validators = validatorDao.selectByExample(example);
            if(validators.size()==0){
                throw new IntercepterFetchException("bean:["+name+"] not exist");
            }
            try {
                bean = context.getBean(validators.get(0).getValidator());
            } catch (BeansException e) {
            }
        }

        if(bean==null){
            throw new IntercepterFetchException("bean:["+name+"] not exist");
        }
        if(!(bean instanceof IRequestIntercepter)){
            throw new IntercepterFetchException("bean:["+name+"] not instance of IRequestIntercepter");
        }
        return (IRequestIntercepter)bean;
    }

}
